package it.isa.demo.controller;

import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Corgile
 * @date 2022-02-26
 * ControllerAdvice的作用之一：请求参数预处理
 */
@ControllerAdvice
public class GlobalData {

	@ExceptionHandler(FileSizeLimitExceededException.class)
	public void maxSizeFile(FileSizeLimitExceededException e, HttpServletResponse response) {
		response.setContentType("text/html;charset=utf-8");
		try {
			PrintWriter out = response.getWriter();
			out.write("<h1>上传文件大小超过限制</h1>");
			out.flush();
			out.close();
		} catch (IOException ioException) {
			e.printStackTrace();
			ioException.printStackTrace();
		}
	}

	@ModelAttribute("info")
	public Map<String, Object> myData() {
		Map<String, Object> map = new HashMap<>();
		map.put("name", "李达康");
		map.put("position", "市委书记");
		return map;
	}

	@InitBinder(value = "book")
	public void initBook(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("book.");
	}

	@InitBinder(value = "author")
	public void initAuthor(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("author.");
	}
}
